package com.zhu.storesmanager;

import java.text.SimpleDateFormat;

import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.network.HttpConnectionMethod;
import com.zhu.storesmanager.network.HttpUtil;
import com.zhu.storesmanager.network.NetworkCallback;
import com.zhu.storesmanager.network.ParseNetworkData;
import com.zhu.storesmanager.security.DesUtil;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.views.SyncView;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 管理员查看门店拜访日期列表
 */
public class AdminVisitDateActivity extends Activity implements OnClickListener{

	public final static String STORE_ID = "storeId"; //门店ID
	public final static String STORE_NAME = "storeName";
	private final static int NETWORK_DIALOG = 0; //网络进度框
	private final static int MSG_FAIL = 0;
	private final static int MSG_SUCCESS = 1;
	private final static int MSG_CONTENT_SUCCESS = 2; //拜访内容获取成功
	private LinearLayout mBodyView = null; //列表内容数据

	private String mStoreId = null; //门店ID
	private String mStoreName = null; //门店名字
	private SyncModel.QueryVisitResult mQueryVisitResult = null; //门店
	private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mStoreId = getIntent().getStringExtra(STORE_ID);  //获取门店ID
		mStoreName = getIntent().getStringExtra(STORE_NAME); //获取门店名字
		setContentView(R.layout.activity_admin_visitdate);

		setupViews();
		initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupViews(){
		((TextView) findViewById(R.id.title_text)).setText(mStoreName);
		findViewById(R.id.bottom_back).setOnClickListener(this);
		mBodyView = (LinearLayout)findViewById(R.id.body);
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		showDialog(NETWORK_DIALOG);
		//请求区域数据
		new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
            	mQueryVisitResult = ParseNetworkData.parseVisitListResult(result);
            	dismissDialog(NETWORK_DIALOG);
            	if(mQueryVisitResult != null && mQueryVisitResult.Status == SyncModel.SUCCEED){ //请求成功
            		mHandler.sendEmptyMessage(MSG_SUCCESS);
            	}else{ //请求失败
            		mHandler.sendEmptyMessage(MSG_FAIL);
            	}
            }
         }
        ).callPost(HttpUtil.getVisitListUrl(), HttpUtil.getPutVisitListContent(DataUtils.mUserData.mUuid, mStoreId));
	}

	/**
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v != null){
			switch(v.getId()){ //查询
				case R.id.bottom_back: //返回
					finish();
					break;
				case R.id.rowcontent: //列表项
					SyncModel.ResQueryVisit visit = (SyncModel.ResQueryVisit)v.getTag();
					getVisitContent(visit.Id);
					break;
			}
		}
	}

	/**
     * 上传结果消息处理
     */
    private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
            switch (msg.what) {
            	case MSG_SUCCESS:
            		updateBodyView();
            		Actions.toastShort(AdminVisitDateActivity.this, R.string.success_getdata);
            		break;
            	case MSG_FAIL:
            		if(msg != null && msg.obj != null && msg.obj instanceof String){
            			Actions.toastShort(AdminVisitDateActivity.this, (String)msg.obj);
            		}else{
            			Actions.toastShort(AdminVisitDateActivity.this, R.string.fail_getdata);
            		}
            		break;
            	case MSG_CONTENT_SUCCESS:
            		gotoSampleActivity();
            		break;
            }
    	}
    };

    /**
     * 联网进度提示
     */
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case NETWORK_DIALOG:
                ProgressDialog pd = new ProgressDialog(this);
                pd.setMessage(this.getString(R.string.getdata)
                        + getString(R.string.please_wait));
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);
                return pd;
            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    /**
     * 更新界面数据
     */
    private void updateBodyView(){
    	mBodyView.removeAllViews();
    	if(mQueryVisitResult.Data != null){
            for(SyncModel.ResQueryVisit visit : mQueryVisitResult.Data){
            	mBodyView.addView(getVisitListItem(visit));
            }	            	
        }
    }

    /**
     * 获取门店列表项界面
     */
    private View getVisitListItem(SyncModel.ResQueryVisit visit) {
        View row = LayoutInflater.from(this).inflate(R.layout.visitdatelist_item, null);
        View content = row.findViewById(R.id.rowcontent);
        content.setTag(visit);
        content.setOnClickListener(this);
        ((TextView) row.findViewById(R.id.visit_date)).setText(mDateFormat.format(visit.VisitDate));
        ((TextView) row.findViewById(R.id.visit_supervisorName)).setText(visit.SupervisorName);
        return row;
    }

    /**
     * 获取拜访内容数据
     */
    private void getVisitContent(int visitId){
    	showDialog(NETWORK_DIALOG);
		//请求区域数据
		new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
            	DataUtils.mQueryVisitContentResult = ParseNetworkData.parseVisitContentResult(result);
            	if(DataUtils.mQueryVisitContentResult != null && DataUtils.mQueryVisitContentResult.Status == SyncModel.SUCCEED){ //请求成功
            		String salesJson;
					try {
						salesJson = DesUtil.des3DecodeECB2(HttpUtil.mDesKey, DataUtils.mQueryVisitContentResult.Data.SalesDes);
						DataUtils.mDesDataVisitContentSales = ParseNetworkData.parseSalesListResult(salesJson);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

            		if(DataUtils.mProjectResult == null){
            			getProjectContent();
            		}else{
            			dismissDialog(NETWORK_DIALOG);
            			mHandler.sendEmptyMessage(MSG_CONTENT_SUCCESS);
            		}
            	}else{ //请求失败
            		dismissDialog(NETWORK_DIALOG);
            		if(DataUtils.mQueryVisitContentResult != null && DataUtils.mQueryVisitContentResult.Msg != null){
            			mHandler.sendMessage(Message.obtain(mHandler, MSG_FAIL, DataUtils.mQueryVisitContentResult.Msg));
            		}else{
            			mHandler.sendEmptyMessage(MSG_FAIL);
            		}
            		DataUtils.mQueryVisitContentResult = null;
            		DataUtils.mDesDataVisitContentSales = null;
            	}
            }
         }
        ).callPost(HttpUtil.getVisitContentUrl(), HttpUtil.getPutVisitContent(DataUtils.mUserData.mUuid, visitId));
    }

    /**
     * 获取PROJECT内容数据
     */
    private void getProjectContent(){
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	DataUtils.mProjectResult = ParseNetworkData.parseProjectResult(result);
            	dismissDialog(NETWORK_DIALOG);
                if(DataUtils.mProjectResult != null && DataUtils.mProjectResult.Status == SyncModel.SUCCEED){
                    mHandler.sendEmptyMessage(MSG_CONTENT_SUCCESS);
                }else{
                	mHandler.sendEmptyMessage(MSG_FAIL);
            		DataUtils.mQueryVisitContentResult = null;
                }
            }
         }
        ).callPost(HttpUtil.getProjectLabelUrl(), HttpUtil.getPutProjectsContent(DataUtils.mUserData.mUuid));
    }

    /**
     * 跳转出样界面
     */
    private void gotoSampleActivity(){
    	Intent intent = new Intent();
    	intent.setClass(this, SvStoreSampleActivity.class);
    	startActivity(intent);
    }
}
